package com.huixh.train.gateway.filters;

import cn.hutool.core.util.StrUtil;
import com.huixh.train.utils.security.JwtUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author huixh
 */
@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {
    private final static String TOKEN_KEY = "token";
    @Resource
    private JwtUtil jwtUtil;
    private final Logger logger = LoggerFactory.getLogger(LoginMemberFilter.class);

    private static final List<String> MATCHING_PATHS = Arrays.asList(
            "/hello",
            "/captcha",
            "/test",
            "/member/register",
            "/member/test",
            "/member/sendCode",
            "/member/login",
            "/member/doc.html",
            "/member/webjars/js/",
            "/member/webjars/css/",
            "/member/v3/api-docs/swagger-config",
            "/member/favicon.ico",
            "/member/v3/api-docs/business",
            "/member/v3/api-docs/member"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest httpRequest = exchange.getRequest();
        String path = httpRequest.getURI().getPath();

        if (MATCHING_PATHS.stream().anyMatch(path::contains)) {
            return chain.filter(exchange);
        }
        String token = httpRequest.getHeaders().getFirst(TOKEN_KEY);
        logger.info("会员登录验证 token : {}", token);
        if (StrUtil.isBlankIfStr(token)) {
            logger.error("token 为空！");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        if (!jwtUtil.verify(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            logger.error("token 验证失败！");
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
